//
//  AY_BookVpPage.m
//  AiYue
//
//  Created by boWen on 2023/10/26.
//

#import "AY_BookVpPage.h"
#import "AY_BookVpHeader.h"
#import "AY_BookVpCell.h"
#import "AY_BookVpCell2.h"
#import "AY_BookVpFootView.h"
#import "AY_BookPChasePage.h"
#import <WebKit/WebKit.h>
#import "AY_VpCenterUseListPage.h"

@interface AY_BookVpPage ()<UITableViewDelegate, UITableViewDataSource, WKUIDelegate, WKNavigationDelegate, SXBookVpFootViewDelegate>
@property (nonatomic, strong) UITableView * baseTableView;
@property (nonatomic, strong) AY_BookVpHeader * myHeaderView;
@property (nonatomic, strong) AY_BookVpFootView * myFooterView;
@property (nonatomic, strong) NSArray * productList;
@property (nonatomic, strong) NSArray * chaseList;
@property(nonatomic,strong) WKWebView * webView;
@property (nonatomic, strong) NSString * h5Refer;
@property (nonatomic, strong) ConfigModel *configModel;
@property (nonatomic, strong) BannerModel *bannerModel;
@property (nonatomic, strong) NSString *pType;

@property (nonatomic, copy) NSString * vipType;
@property (nonatomic, copy) NSString * orderNo;
@property (nonatomic, strong) UserInfo * userInfoModel;
@end

@implementation AY_BookVpPage

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initWithNav];
    [self getConfigWithNet];
    self.pType = @"ZFB";
    [self getData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zgStatus) name:ZFREFRESH object:nil];
}

- (void)getData {
    [AYApiRequest getUserInfoSuccess:^(AY_UserModel * _Nonnull pkg) {
        if([pkg.code isEqualToString:@"200"]) {
            self.userInfoModel = pkg.data;
            self.myHeaderView.infoModel = self.userInfoModel;
            self.vipType = pkg.data.vipType;
            [self.baseTableView reloadData];
        }
    } failure:^(int status, NSString * _Nonnull info) {
        ShowToast(@"亲，网络不顺畅哟~");
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self barStyleLight];
    [self.myFooterView initTimer];
}

- (void)zgStatus {
    [AYApiRequest getOrderStatus:self.orderNo Success:^(AY_ConfigModel * _Nonnull pkg) {
        if (!kStringIsEmpty(self.orderNo)) {
            ShowToast(pkg.msg);
        }
    } failure:^(int status, NSString * _Nonnull info) {
    }];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self barStyleBlack];
    self.myFooterView.timer = nil;
    [self.myFooterView.timer invalidate];
    [[NSNotificationCenter defaultCenter] postNotificationName:ZFREFRESH object:nil];
}

- (void)initWithNav {
    
    self.gk_navTitle = [NSString stringWithFormat:@"%@VIP",[AYMMKV getStringForKey:KT]];
    self.gk_navTitleColor = COLOR(@"#ffffff");
    self.gk_navBackgroundColor = COLOR(@"#1a171a");
    self.gk_navLeftBarButtonItem = [UIBarButtonItem itemWithImageName:@"AY_nav_pop_w" target:self action:@selector(popVC)];
    self.gk_navItemRightSpace = YNUM(12);
    
    UIButton *xfBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [xfBtn setTitle:@"消费记录  " forState:UIControlStateNormal];
    [xfBtn setTitleColor:COLOR(@"f9d5bb") forState:UIControlStateNormal];
    [xfBtn addTarget:self action:@selector(useListPage) forControlEvents:UIControlEventTouchUpInside];
    xfBtn.titleLabel.font = YFont(14);
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:xfBtn];
    self.gk_navRightBarButtonItem = item;
    
    [self.view addSubview:self.baseTableView];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.myFooterView];
}


-(void)popVC{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)useListPage {
    AY_VpCenterUseListPage * vpPage = [AY_VpCenterUseListPage new];
    [self.navigationController pushViewController:vpPage animated:YES];
}

- (void)getConfigWithNet {
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    [AYApiRequest getPackageProductListWithAssetType:@"2" Success:^(AY_BookVpModel * _Nonnull pkg) {
        dispatch_group_leave(group);
        if([pkg.code isEqualToString:@"200"]) {
            self.productList = pkg.data;
            if(self.productList.count > 0 ) {
                self.myHeaderView.vpModel = self.productList[0];
                [self.myFooterView sendVpProductModel:self.productList[0] andPType:self.pType];
            }
        }
    } failure:^(int status, NSString * _Nonnull info) {
        dispatch_group_leave(group);
    }];
    
    dispatch_group_enter(group);
    [AYApiRequest getPackagePymentTypeListSuccess:^(AY_PyChaseModel * _Nonnull pkg) {
        dispatch_group_leave(group);
        if([pkg.code isEqualToString:@"200"]) {
            self.chaseList = pkg.data;
        }
    } failure:^(int status, NSString * _Nonnull info) {
        dispatch_group_leave(group);
    }];
    
    dispatch_group_enter(group);
    [AYApiRequest APPConfigSuccess:^(AY_ConfigModel * _Nonnull pkg) {
        self.configModel = pkg.data;
        dispatch_group_leave(group);
    } failure:^(int status, NSString * _Nonnull info) {
        dispatch_group_leave(group);
    }];
    
    dispatch_group_enter(group);
    [AYApiRequest getBannerInfoWithCode:@"vip_banner" Success:^(AY_BannerInfoModel * _Nonnull pkg) {
        self.bannerModel = pkg.data;
        dispatch_group_leave(group);
    } failure:^(int status, NSString * _Nonnull info) {
        dispatch_group_leave(group);
    }];

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self.baseTableView reloadData];
    });
      
}

#pragma mark - zfb
- (void)ktAction {
    [self pWithType:self.pType];
}

- (UITableView *)baseTableView {
    if (!_baseTableView) {
        UITableView * myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, GK_SCREEN_WIDTH, GK_SCREEN_HEIGHT - GK_STATUSBAR_NAVBAR_HEIGHT - YNUM(100)) style:UITableViewStylePlain];
        if (@available(iOS 11.0, *)) {
            myTableView.contentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 15.0, *)) {
            myTableView.sectionHeaderTopPadding = 0;
        }
        myTableView.showsVerticalScrollIndicator = NO;
        myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        myTableView.backgroundColor = COLOR_Bg;
        myTableView.delegate = self;
        myTableView.dataSource = self;
        myTableView.backgroundColor = [UIColor whiteColor];
        myTableView.tableHeaderView = self.myHeaderView;
        [myTableView registerClass:[AY_BookVpCell class] forCellReuseIdentifier:@"AY_BookVpCell"];
        [myTableView registerClass:[AY_BookVpCell2 class] forCellReuseIdentifier:@"AY_BookVpCell2"];
        _baseTableView = myTableView;
    }
    return _baseTableView;
}

- (NSArray *)productList {
    if(!_productList) {
        _productList = [NSArray array];
    }
    return _productList;
}

- (NSArray *)chaseList {
    if(!_chaseList) {
        _chaseList = [NSArray array];
    }
    return _chaseList;
}

- (AY_BookVpHeader *)myHeaderView {
    if(!_myHeaderView) {
        _myHeaderView = [[AY_BookVpHeader alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, YNUM(235))];
        _myHeaderView.vipType = self.vipType;
    }
    return _myHeaderView;;
}

- (AY_BookVpFootView *)myFooterView {
    if(!_myFooterView) {
        _myFooterView = [[AY_BookVpFootView alloc] initWithFrame:CGRectMake(0, SCREEN_H - YNUM(125), SCREEN_W, YNUM(125))];
        _myFooterView.delegate = self;
        _myFooterView.backgroundColor = [UIColor clearColor];
        Weak_Self
        _myFooterView.kaitBlock = ^{
            [weakSelf pyChaseWithAction];
        };
    }
    return _myFooterView;
}

#pragma mark - UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row == 0) {
        AY_BookVpCell * cell = [tableView dequeueReusableCellWithIdentifier:@"AY_BookVpCell"];
        cell.vpDataAry = self.productList;
        Weak_Self
        cell.vpUpdateBlock = ^(NSInteger indx) {
            if(weakSelf.productList.count > indx) {
                weakSelf.myHeaderView.vpModel = weakSelf.productList[indx];
                [weakSelf.myFooterView sendVpProductModel:weakSelf.productList[indx] andPType:weakSelf.pType];
            }
        };
        return cell;
    }else if(indexPath.row == 1) {
        AY_BookVpCell2 * cell = [tableView dequeueReusableCellWithIdentifier:@"AY_BookVpCell2"];
        [cell sendConfigModel:self.configModel andBannerModel:self.bannerModel];
        return cell;
    }else {
        static NSString *ID = @"UITableViewCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row == 0) {
        return YNUM(202);
    }else if(indexPath.row == 1) {
        return [self.baseTableView fd_heightForCellWithIdentifier:@"AY_BookVpCell2" configuration:^(id cell) {
            [self setupOfCell:cell atIndexPath:indexPath];
        }];
    }else {
        return YNUM(50);
    }
}

- (void)setupOfCell:(AY_BookVpCell2 *)cell atIndexPath:(NSIndexPath *)indexPath {
    [cell sendConfigModel:self.configModel andBannerModel:self.bannerModel];
}

- (void)pyChaseWithAction {
    NSMutableArray * dataArry = [NSMutableArray array];
    if (self.chaseList.count > 0) {
        for (ChaseModel * model in self.chaseList) {
            NSMutableDictionary * paramDic = [NSMutableDictionary dictionary];
            [paramDic setValue:kStringUtils(model.typeName) forKey:@"typeName"];
            [paramDic setValue:kStringUtils(model.typeCoverUrl) forKey:@"typeCoverUrl"];
            [paramDic setValue:kStringUtils(model.typeCode) forKey:@"type"];
            [dataArry addObject:paramDic];
        }
    }
    AY_BookPChasePage *pop = [[AY_BookPChasePage alloc]initChaseWithInfo:self.myFooterView.vpModel.giveTipStr vc:self dataSource:dataArry andPtype:self.pType];
    STPopupController *popVericodeController = [[STPopupController alloc] initWithRootViewController:pop];
    popVericodeController.style = STPopupStyleBottomSheet;
    [popVericodeController presentInViewController:self];
    pop.pyType = ^(NSString *type) {
        self.pType = type;
        [self.myFooterView sendVpProductModel:self.myFooterView.vpModel andPType:type];
    };
}

- (void)pWithType:(NSString *)type {
    self.myFooterView.ktBtn.hidden = YES;
    self.myFooterView.loadingBack.hidden = NO;
    [AYApiRequest createOrdeWithPymentType:type productId:self.myFooterView.vpModel.vpId productName:self.myFooterView.vpModel.productName articleId:self.bookId Success:^(AY_SignModel * _Nonnull pkg) {
        if ([pkg.code isEqual:@"200"]) {
            SignOwnModel *model = pkg.data;
            self.orderNo = model.outTradeNo;
            [self loadWebViewWithUrl:model.thirdOrderData withRechargeType:type andModel:model];
        }else {
            self.myFooterView.ktBtn.hidden = NO;
            self.myFooterView.loadingBack.hidden = YES;
            ShowToast(pkg.msg);
        }
    } failure:^(int status, NSString * _Nonnull info) {
        self.myFooterView.ktBtn.hidden = NO;
        self.myFooterView.loadingBack.hidden = YES;
    }];
}

- (void)loadWebViewWithUrl:(NSString *)url withRechargeType:(NSString *)rechargeType andModel:(SignOwnModel *)model {
    _webView = [[WKWebView alloc]initWithFrame:CGRectZero];
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    self.h5Refer = model.h5Refer;
    
    if ([rechargeType isEqual:@"WX"]) {
        NSMutableURLRequest * request  = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
        [request setValue:[self getRefer] forHTTPHeaderField:@"Referer"];
        [_webView loadRequest:request];
    }else {
        [_webView loadHTMLString:url baseURL:nil];
        
    }
    [self.view addSubview:_webView];
}

- (NSString *)getRefer {
    if ([self.h5Refer rangeOfString:@"https://"].location != NSNotFound) {
        NSString *refresh = [NSString stringWithFormat:@"%@://",[self.h5Refer stringByReplacingOccurrencesOfString:@"https://" withString:@"www."]];
        return [NSString stringWithFormat:@"%@://",refresh];
    }else if ([self.h5Refer rangeOfString:@"http://"].location != NSNotFound) {
        NSString *refresh = [NSString stringWithFormat:@"%@://",[self.h5Refer stringByReplacingOccurrencesOfString:@"http://" withString:@"www."]];
        return [NSString stringWithFormat:@"%@://",refresh];
    }else {
        return self.h5Refer;
    }
}

#pragma mark - WebViewDelegate
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSLog(@"111>>>>>加载完成");
    
}

-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSURL *URL = navigationAction.request.URL;
    NSString * urlStr = URL.absoluteString;
    NSString * idStr = [AYMMKV getStringForKey:AP];
    idStr = [idStr stringByAppendingString:@"://"];
    
    if ([urlStr containsString:idStr]) {
        NSString * resultUrl = [self URLDecodedString:urlStr];
        NSString* dataStr = [resultUrl substringFromIndex:23];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[dataStr dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
        NSMutableDictionary * mutDict = [[NSMutableDictionary alloc]initWithDictionary:dict];
        [mutDict setObject:SXAPPBUNDLEID forKey:@"fromAppUrlScheme"];
        NSString * dictStr = [self arrayToJSONString:mutDict];
        NSString * ecodeUrl = [self URLEncodedStringWithUrl:dictStr];
        NSString * resultStr = [NSString stringWithFormat:@"%@://%@client/?%@",[AYMMKV getStringForKey:AP],[AYMMKV getStringForKey:AP],ecodeUrl];
        NSURL * url = [NSURL URLWithString:resultStr];
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];

        decisionHandler(WKNavigationActionPolicyCancel);
        self.myFooterView.ktBtn.hidden = NO;
        self.myFooterView.loadingBack.hidden = YES;
        return;
    }else if([urlStr containsString:[NSString stringWithFormat:@"%@://",[AYMMKV getStringForKey:WX]]]) {
        if (![urlStr containsString:@"redirect_url="]) {
            NSString * redirect = [NSString stringWithFormat:@"&redirect_url=%@",self.h5Refer];
            urlStr = [urlStr stringByAppendingString:redirect];
        }
        NSURL * url = [NSURL URLWithString:urlStr];
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        decisionHandler(WKNavigationActionPolicyCancel);
        self.myFooterView.ktBtn.hidden = NO;
        self.myFooterView.loadingBack.hidden = YES;
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (NSString *)URLDecodedString:(NSString *)url
{
    NSString *decodedString  = ( NSString *)CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                                      (__bridge CFStringRef)url,
                                                                                                                      CFSTR(""),
                                                                                                                      CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)));
    return decodedString;
}

- (NSString *)arrayToJSONString:(id)object
{
    NSError *error = nil;
    if (object == nil) {
        return @"";
    }else {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&error];
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        return jsonString;
    }
}

- (NSString *)URLEncodedStringWithUrl:(NSString* )url {
    
    NSString *encodedString = (NSString* )CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)url,NULL,(CFStringRef) @"!'();:@&+$,%#[]|",kCFStringEncodingUTF8));
    
    return encodedString;
}

@end
